Add Python parser via tree-sitter - #23
Open
awe-srush wants to merge 1 commit into
Open
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds
PythonParser, the first concrete implementation ofTreeSitterParserBase, enabling Vanir to detect missing security patches in Python source code. Implements all three language-specific abstract methods required by the base class.Depends on:
feat/tree-sitter-integration(base class)bug/fix-subclass-discovery(recursive subclass registration)feat/python-parser-deps(tree-sitter pip dependencies)feat/python-parser-build(Bazel build targets)Objective
Extend Vanir's patch detection pipeline to support
.pyfiles by plugging a tree-sitter-backed Python parser into the existingAbstractLanguageParsercontract. Once registered, the parser is auto-discovered byget_parser_class()and requires no changes to any upstream Vanir logic.Files
vanir/language_parsers/python/python_parser.pyPythonParserimplementationvanir/language_parsers/python/__init__.pyvanir/language_parsers/language_parsers.pyImplementation
Module-level setup
Tree-sitter imports are guarded with
try/except ImportErrorso the module is safely importable on Python 3.9, wheretree-sitterandtree-sitter-pythonare not installed:Two queries are compiled once at module import (never per file):
_FUNC_QUERY, matches everyfunction_definitionnode, capturing:@func.def, the full function node@func.name, the function name identifier@func.body, the function body block_LOCALS_QUERY, matches five assignment/call patterns to collect local variables and called functions:(assignment left: (_) @assign.lhs), standard assignments(augmented_assignment left: (identifier) @aug.lhs),+=,-=etc.(for_statement left: (_) @for.lhs), loop variables(named_expression name: (identifier) @walrus.name), walrus operator:=(call function: (identifier) @call.name), direct function callsPythonParser(class)Thin subclass of
TreeSitterParserBase. Sets four class-level attributes:LANGUAGE = _PY_LANGUAGE, compiled Python grammar_FUNC_QUERY = _FUNC_QUERY, function discovery querySKIP_TOKEN_TYPES, prunescomment,newline,indent,dedent,line_continuationfrom token collectionSTRING_NODE_TYPE = 'string', Python string nodes emitted as single tokensget_supported_extensions()Returns
['.py']when tree-sitter is available,[]on Python 3.9, causing the dispatcher to silently skip.pyfiles rather than raise an error.Abstract method implementations
_extract_param_names(params_node) → list[str]Walks
params_node.named_childrenand resolves each to a plain name string via the module-level helper_get_param_name()._get_param_name()handles all Python parameter node types:identifier, plain param (x)typed_parameter, annotated param (x: int)default_parameter, param with default (x=0)typed_default_parameter, annotated with default (x: int = 0)list_splat_pattern, variadic positional (*args)dictionary_splat_pattern, variadic keyword (**kwargs)*separator, returned asNoneand skippedFor all compound types, the function finds the first identifier child node and decodes its text.
_extract_annotations(func_node) → (return_types, used_data_types)Extracts Python type annotations from a
function_definitionnode:Return type annotation:
return_typefield viachild_by_field_name('return_type')_flat_tokens_cursor()return_types = [[token, ...]]or[]if no annotationParameter type annotations:
parametersnamed childrentyped_parameterortyped_default_parameter, retrieves thetypefield viachild_by_field_name('type')used_data_types = [[token, ...], ...], one list per annotated param_collect_locals_calls(body_node, nested_ranges) → (local_vars, called_fns)Uses
QueryCursor(_LOCALS_QUERY).captures(body_node)to collect all assignment targets and call names within the function body.Each captured node is filtered through
_is_nested(), any node whosestart_bytefalls within a nested function's byte range is excluded, preventing inner-scope variables from leaking into the outer function's Vanir signature.Capture groups processed:
assign.lhs, passed to_collect_ids_from_lhs()which handles plain identifiers, tuple unpacking (a, b = ...), and pattern listsaug.lhs, augmented assignment targets, added directly if identifierfor.lhs, for-loop variables, passed to_collect_ids_from_lhs()walrus.name, walrus operator targets (:=), added if identifiercall.name, direct function call names, added tocalled_fnsRuntime availability
Vanir runs on Python 3.9 through 3.13. The tree-sitter packages are not installed for Python 3.9, so when Vanir itself runs on 3.9,
get_supported_extensions()returns[]and.pyfiles are silently skipped with no error.On Python 3.10 and above, the parser is fully active.
Debug harness
python_parser.pyincludes a__main__block for local inspection during development. It is never executed when Vanir imports the module.Run directly to inspect parser output on any
.pyfile:If no file is provided, it runs against a built-in sample covering classes, annotated methods, async functions, walrus operator, and tuple unpacking.
Prints all extracted chunks (name, parameters, return types, local variables, called functions, tokens, normalized form) and also runs an error handling test on intentionally broken Python to verify
ParseErrorcollection.Dependencies
Must be merged after:
feat/tree-sitter-integrationbug/fix-subclass-discoveryfeat/python-parser-depsfeat/python-parser-builddocs/python-parserfollows this PR.